import requests  #---------------OAV16存储------------------------
def cunchu_oav16():
    # 定义变量
    ip_address = 'x.x.x.x'
    port = '8088'

    # 构造完整的URL
    url = f'https://{ip_address}:{port}/deviceManager/rest/xxxxx/sessions'

    # 定义需要传递的参数
    payload = {
        'username': 'xxxxxxxxxxxxxx',
        'password': 'xxxxxxxxxxxxxxxxxxx',
        'scope': '0'
    }

    # 发起 POST 请求
    requests.packages.urllib3.disable_warnings()
    response = requests.post(url, json=payload, verify=False)  # 关闭 SSL 验证，请谨慎使用

    # 检查响应状态码
    if response.status_code == 200:
        data = response.json()  # 将响应内容转换为 JSON 格式
        cookies = response.cookies  # 获取响应中的Cookie信息
        formatted_cookies = '; '.join([f"{cookie.name}={cookie.value}" for cookie in cookies])
        iBaseToken = data['data']['iBaseToken']  # 获取 iBaseToken 的值
        deviceid = data['data']['deviceid']  # 获取 deviceid 的值
        print(deviceid)
        print(iBaseToken)
        print(formatted_cookies)
    # ----------------查询设备状态信息------------------
        status_url = f'https://{ip_address}:{port}/deviceManager/rest/{deviceid}/server/status'
        headers = {
            'Cookie': formatted_cookies,
            'iBaseToken': iBaseToken
        }
        status_response = requests.get(status_url, headers=headers, verify=False)
        status_mapping = {
            0: '正常',
            1: '异常',
            2: '上电中',
            3: '下电中',
            4: '安全保护状态',
            5: '升级中',
            6: '掉电',
            7: '离线'
        }

        if status_response.status_code == 200:
            status_data = status_response.json()
            if 'data' in status_data and 'status' in status_data['data']:
                device_status_code = status_data['data']['status']
                if device_status_code in status_mapping:
                    oa_device_status_description = status_mapping[device_status_code]
                    print("设备状态:", oa_device_status_description)
                else:
                    print("未知状态码:", device_status_code)
            else:
                print("未找到设备状态信息")
        else:
            print('设备状态信息查询失败，状态码：', status_response.status_code)
    # ------------------------查询当前告警信息——-----------------------
        alarm_url = f'https://{ip_address}:{port}/deviceManager/rest/{deviceid}/alarm/currentalarm'
        alarm_response = requests.get(alarm_url, headers=headers, verify=False)
        oa_alarm_details = ['无告警信息']  # 设置默认值为一个包含'无告警信息'的列表

        if alarm_response.status_code == 200:
            alarm_data = alarm_response.json()
            if 'data' in alarm_data and alarm_data['data']:
                alarms = alarm_data['data']
                # 获取所有告警的详细信息
                oa_alarm_details = [alarm.get('detail', '无告警信息') for alarm in alarms]

                print("告警详情:", oa_alarm_details)
            else:
                print("无告警信息")
        else:
            print('告警信息查询失败，状态码：', alarm_response.status_code)
        # ---------------------当前告警个数----------------------
        num_alarm = f'https://{ip_address}:{port}/deviceManager/rest/{deviceid}/alarm/currentalarm/count'
        num_response = requests.get(num_alarm, headers=headers, verify=False)
        if num_response.status_code == 200:
            num_data = num_response.json()
            if 'data' in num_data and 'COUNT' in num_data['data']:
                oa_num_alarms = num_data['data']['COUNT']
                print("当前告警个数:", oa_num_alarms)
            else:
                print("未找到告警个数信息")
        else:
            print('告警个数信息查询失败，状态码：', num_response.status_code)
        # -----------------查询文件系统信息----------------------------
        print("-----------------------文件系统信息------------------------")
        system_url = f'https://{ip_address}:{port}/deviceManager/rest/{deviceid}/filesystem'
        system_response = requests.get(system_url, headers=headers, verify=False)
        if system_response.status_code == 200:
            system_data = system_response.json()

            if 'data' in system_data:
                oa_file_systems = system_data['data']
                oa_system_data = []
                for fs in oa_file_systems:
                    doc_name = fs.get('NAME', '未知')
                    total_capacity = fs.get('CAPACITY', '未知')
                    used_capacity = fs.get('AVAILABLECAPCITY', '未知')
                    #计算使用率
                    availableandalloccappacitypatio = fs.get('AVAILABLEANDALLOCCAPACITYRATIO', 'N/A')
                    availableandalloccappacitypatio = round(float(availableandalloccappacitypatio))
                    if availableandalloccappacitypatio > 80:
                        availableandalloccappacitypatio = f'<span style="color:red;">{availableandalloccappacitypatio}%</span>'
                    else:
                        availableandalloccappacitypatio = f'<span style="color:green;">{availableandalloccappacitypatio}%</span>'

                    total_capacity = round(float(total_capacity) * 512 / 1024 / 1024 / 1024 / 1024, 3)
                    if total_capacity < 1:  # 如果小于1T，单位转为GB
                        total_capacity = round(total_capacity * 1024, 3)
                        total_capacity = f'{total_capacity} GB'
                    else:
                        total_capacity = f'{total_capacity} TB'

                    used_capacity = round(float(used_capacity) * 512 / 1024 / 1024 / 1024, 3)
                    if used_capacity > 1000:  # 如果大于1000，单位转为TB
                        used_capacity = round(used_capacity / 1024, 3)
                        used_capacity = f'{used_capacity} TB'
                    else:
                        used_capacity = f'{used_capacity} GB'
                    parent_name = fs.get('PARENTNAME', '未知')
                    health_status = fs.get('HEALTHSTATUS', '未知')
                    health_status = int(health_status)
                    if health_status == 1:
                        health_status = "健康"
                    else:
                        health_status = "异常"
                    running_status = fs.get('RUNNINGSTATUS', '未知')
                    running_status = int(running_status)
                    if running_status == 27:
                        running_status = "在线"
                    else:
                        running_status = "异常"

                    # 将文件系统数据添加到列表
                    oa_system_data.append({
                        'doc_name': doc_name,
                        'total_capacity': total_capacity,
                        'used_capacity': used_capacity,
                        'health_status': health_status,
                        'running_status': running_status,
                        'parent_name': parent_name,
                        'availableandalloccappacitypatio': availableandalloccappacitypatio
                    })

            else:
                print("未找到文件系统信息")
        else:
            print('文件系统信息查询失败，状态码：', system_response.status_code)
    # -------------------批量查询存储池信息---------------------
        print("-----------------存储池信息----------------------")
        storagepool_url = f'https://{ip_address}:{port}/deviceManager/rest/{deviceid}/storagepool'
        storage_response = requests.get(storagepool_url, headers=headers, verify=False)
        if storage_response.status_code == 200:
            storage_data = storage_response.json()
            if 'data' in storage_data:
                oa_storage_pools = storage_data['data']
                # 假设存储池信息是一个列表，遍历每个存储池字典
                oa_storage_data = []
                for storage_pool in oa_storage_pools:
                    # 从每个存储池字典中获取特定的键值对
                    name = storage_pool.get("NAME", "未知")
                    health_status = storage_pool.get('HEALTHSTATUS', '未知')
                    health_status = int(health_status)
                    if health_status == 1:
                        health_status = "健康"
                    else:
                        health_status = "异常"
                    running_status = storage_pool.get('RUNNINGSTATUS', '未知')
                    running_status = int(running_status)
                    if running_status == 27:
                        running_status = "在线"
                    else:
                        running_status = "异常"
                    parent_name = storage_pool.get("PARENTNAME", "未知")
                    user_total_capacity = storage_pool.get("USERTOTALCAPACITY", "未知")
                    user_consumed_capacity = storage_pool.get("USERCONSUMEDCAPACITY", "未知")
                    oauser_total_capacity = round(float(user_total_capacity) * 512 / 1024 / 1024 / 1024 , 3)
                    oauser_consumed_capacity = round(float(user_consumed_capacity) * 512 / 1024 / 1024 / 1024 , 3)
                    #使用率
                    oa_shiyong_baifenbi = round(float(oauser_consumed_capacity / oauser_total_capacity) * 100,3)
                    if oa_shiyong_baifenbi > 80:
                        oa_shiyong_baifenbi = f'<span style="color:red;">{oa_shiyong_baifenbi}%</span>'
                    else:
                        oa_shiyong_baifenbi = f'<span style="color:green;">{oa_shiyong_baifenbi}%</span>'

                    user_total_capacity = round(float(user_total_capacity) * 512 / 1024 / 1024 / 1024 / 1024, 3)
                    if user_total_capacity < 1:  # 如果小于1T，单位转为GB
                        user_total_capacity = round(user_total_capacity * 1024, 3)
                        user_total_capacity = f'{user_total_capacity} GB'
                    else:
                        user_total_capacity = f'{user_total_capacity} TB'

                    user_consumed_capacity = round(float(user_consumed_capacity) * 512 / 1024 / 1024 / 1024 / 1024, 3)
                    if user_consumed_capacity < 1:  # 如果小于1T，单位转为GB
                        user_consumed_capacity = round(user_consumed_capacity * 1024, 3)
                        user_consumed_capacity = f'{user_consumed_capacity} GB'
                    else:
                        user_consumed_capacity = f'{user_consumed_capacity} TB'
                    user_free_capacity = storage_pool.get("USERFREECAPACITY", "未知")
                    user_free_capacity = round(float(user_free_capacity) * 512 / 1024 / 1024 / 1024 / 1024, 3)
                    if user_free_capacity < 1:  # 如果小于1T，单位转为GB
                        user_free_capacity = round(user_free_capacity * 1024, 3)
                        user_free_capacity = f'{user_free_capacity} GB'
                    else:
                        user_free_capacity = f'{user_free_capacity} TB'

                    #
                    oa_storage_data.append({
                        'name': name,
                        'user_total_capacity': user_total_capacity,
                        'user_consumed_capacity': user_consumed_capacity,
                        'user_free_capacity': user_free_capacity,
                        'health_status': health_status,
                        'running_status': running_status,
                        'oa_shiyong_baifenbi': oa_shiyong_baifenbi
                    })


        else:
            print('存储池信息查询失败，状态码：', storage_response.status_code)
    else:
        print('登录失败，状态码：', response.status_code)
    return {
        'oa_device_status_description': oa_device_status_description,
        'oa_num_alarms': oa_num_alarms,
        'oa_alarm_details': oa_alarm_details,
        'oa_file_systems': oa_system_data,
        'oa_storage_pools': oa_storage_data,
    }
# cunchu_oav16()